import { defineStore } from 'pinia'
import { ref } from 'vue'
import { GET_TOKEN } from '@/utils/token'
import pinia from '..'
import { AddChatMessageParams, chatMessageBaseType } from '@/api/chat/type'
import { MES_WS_API, reqAddChatMessage } from '@/api/chat'
import { ElMessage } from 'element-plus'

const useUserMessageStore = defineStore('userMessage', () => {
  const chatWebsocket = ref<WebSocket>()
  const chatMessages = ref<chatMessageBaseType[]>([])

  function createChatWebSocket(url: string) {
    const chatWS = new WebSocket(url)
    chatWS.onopen = () => {
      console.log(`chatWebSocket connected`)
    }
    chatWS.onmessage = (msg) => {
      const chatMessage = JSON.parse(msg.data)
      chatMessages.value = [...chatMessages.value, chatMessage]
    }
    chatWS.onerror = (error) => {
      console.log(`chatWebSocket error: ${error}`)
    }
    chatWS.onclose = () => {
      console.log(`chatWebSocket closed`)
    }
    chatWebsocket.value = chatWS
  }

  async function chatWSConnect(targetUsername: string) {
    await createChatWebSocket(
      MES_WS_API.CHAT_WS_API.replace(
        '{targetUsername}',
        targetUsername,
      ).replace('{token}', GET_TOKEN()),
    )
  }

  async function sendMessage(chatMessage: AddChatMessageParams) {
    try {
      await reqAddChatMessage(chatMessage)
    } catch (error) {
      ElMessage.error((error as Error).message)
    }
  }

  return {
    chatWebsocket,
    chatMessages,
    chatWSConnect,
    sendMessage,
  }
})
export default useUserMessageStore

// 非setup
export function useUserMessageStoreHook() {
  return useUserMessageStore(pinia)
}
